<%
	-- Copyright 2018-2020 sb <sb@gmail.com>
	local api = require "luci.model.cbi.passwall.api.api"
	local dsp = require "luci.dispatcher"
	
	local tcp_node_num = api.uci_get_type("global_other", "tcp_node_num", 1)
	local udp_node_num = api.uci_get_type("global_other", "udp_node_num", 1)
	local socks_node_num = api.uci_get_type("global_other", "socks_node_num", 1)
	local compact_display_nodes = api.uci_get_type("global_other", "compact_display_nodes", 1)
-%>

<style>
table th, .table .th {
	text-align: center;
}

table td, .table .td {
	text-align: center;
    white-space: nowrap;
    word-break: keep-all;
}

#set_node_div{
	display: none;
	width: 30rem;
	position: fixed;
	left:50%;
	top:50%;
	transform: translate(-50%, -50%);
	padding-top: 30px;
	z-index: 99;
	text-align: center;
	background: white;
    box-shadow: darkgrey 10px 10px 30px 5px;
}
</style>

<script type="text/javascript">
	//<![CDATA[
	var ajax = {
		post: function(url, data, fn_success, fn_timeout) {
			var xhr = new XMLHttpRequest();
			var code = ajax.encode(data);
			xhr.open("POST", url, true);
			xhr.timeout = 1000;
			xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			xhr.ontimeout = function() {
				fn_timeout(xhr);
			}
			xhr.onreadystatechange = function() {
				if(xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 304)) {
					var json = null;
					if (xhr.getResponseHeader("Content-Type") == "application/json") {
						try {
							json = eval('(' + xhr.responseText + ')');
						}
						catch(e) {
							json = null;
						}
					}
					fn_success(xhr, json);
				}
			};
			xhr.send(code);
		},
		encode: function(obj) {
			obj = obj ? obj : { };
			obj['_'] = Math.random();

			if (typeof obj == 'object')
			{
				var code = '';
				var self = this;

				for (var k in obj)
					code += (code ? '&' : '') +
						k + '=' + encodeURIComponent(obj[k]);

				return code;
			}

			return obj;
		}
	}
	
	var section = "";
	function open_set_node_div(cbi_id) {
		section = cbi_id;
		document.getElementById("set_node_div").style.display="block";
		var node_name = document.getElementById("cbid.passwall." + cbi_id + ".remarks").value;
		document.getElementById("set_node_name").innerHTML = node_name;
	}
	
	function close_set_node_div() {
		document.getElementById("set_node_div").style.display="none";
		document.getElementById("set_node_name").innerHTML = "";
	}
	
	function set_node(protocol,number) {
		if (confirm('<%:Are you sure set to%> ' + protocol.toUpperCase() + "_" + number + '<%:the server?%>')==true){
			window.location.href = '<%=dsp.build_url("admin/services/passwall/set_node")%>?protocol=' + protocol + '&number=' + number + '&section=' + section;
		}
	}
	
	function ping_node(cbi_id,dom) {
		<% if compact_display_nodes and tonumber(compact_display_nodes) == 1 then %>
			var remarks = document.getElementById("cbid.passwall." + cbi_id + ".remarks").value;
			var address = null;
			var port = null;
			if (remarks.lastIndexOf("（") != -1 && remarks.lastIndexOf("）") != -1) {
				var address_full = remarks.substring(remarks.lastIndexOf("（") + 1, remarks.lastIndexOf("）"));
				address = address_full.substring(0, address_full.lastIndexOf(":"));
				port = address_full.substring(address_full.lastIndexOf(":") + 1);
			}
		<% else %>
			var address = document.getElementById("cbid.passwall." + cbi_id + ".address").value;
			var port = document.getElementById("cbid.passwall." + cbi_id + ".port").value;
		<% end %>
		if ((address != null && address != "") && (port != null && port != "")) {
			XHR.get('<%=dsp.build_url("admin/services/passwall/ping_node")%>', {
					address: address,
					port: port
				},
				function(x, result) {
					if(x && x.status == 200) {
						if (result.ping == null || result.ping.trim() == "") {
							dom.outerHTML = "<font style='color:red'><%:Timeout%></font>";
						} else {
							var ping = parseInt(result.ping);
							if (ping < 100)
								dom.outerHTML = "<font style='color:green'>" + result.ping + " ms" + "</font>";
							else if (ping < 200)
								dom.outerHTML = "<font style='color:#fb9a05'>" + result.ping + " ms" + "</font>";
							else if (ping >= 200)
								dom.outerHTML = "<font style='color:red'>" + result.ping + " ms" + "</font>";
						}
					}
				}
			);
		}
	}
	
	/* 自动Ping */
	const auto_ping_value = document.getElementsByClassName('auto_ping_value');
	var index = 0;
	function auto_ping() {
		if (index >= auto_ping_value.length) { 
			return;
		}
		var has_ping = auto_ping_value[index].getAttribute("has_ping");
		if (has_ping == null) {
			var cbi_id = auto_ping_value[index].getAttribute("cbiid");
			<% if compact_display_nodes and tonumber(compact_display_nodes) == 1 then %>
				var remarks = document.getElementById("cbid.passwall." + cbi_id + ".remarks").value;
				var address = null;
				var port = null;
				if (remarks.lastIndexOf("（") != -1 && remarks.lastIndexOf("）") != -1) {
					var address_full = remarks.substring(remarks.lastIndexOf("（") + 1, remarks.lastIndexOf("）"));
					address = address_full.substring(0, address_full.lastIndexOf(":"));
					port = address_full.substring(address_full.lastIndexOf(":") + 1);
				}
			<% else %>
				var address = document.getElementById("cbid.passwall." + cbi_id + ".address").value;
				var port = document.getElementById("cbid.passwall." + cbi_id + ".port").value;
			<% end %>
			//判断是否含有汉字
			var reg = new RegExp("[\\u4E00-\\u9FFF]+","g");
			if ((address != null && address != "") && (port != null && port != "") && reg.test(address) == false && (address.indexOf(".") != -1 && address.charAt(address.address - 1) != ".")) {
				ajax.post('<%=dsp.build_url("admin/services/passwall/ping_node")%>', {
						index: index,
						address: address,
						port: port
					},
					function(x, result) {
						if(x && x.status == 200) {
							for(var i = 0; i < auto_ping_value.length; i++) {
								var obj = auto_ping_value[i];
								var obj_cbi_id = obj.getAttribute("cbiid");
								<% if compact_display_nodes and tonumber(compact_display_nodes) == 1 then %>
									var obj_remarks = document.getElementById("cbid.passwall." + obj_cbi_id + ".remarks").value;
									var obj_address = null;
									var obj_port = null;
									if (obj_remarks.lastIndexOf("（") != -1 && obj_remarks.lastIndexOf("）") != -1) {
										var obj_address_full = obj_remarks.substring(obj_remarks.lastIndexOf("（") + 1, obj_remarks.lastIndexOf("）"));
										obj_address = obj_address_full.substring(0, obj_address_full.lastIndexOf(":"));
										obj_port = obj_address_full.substring(obj_address_full.lastIndexOf(":") + 1);
									}
								<% else %>
									var obj_address = document.getElementById("cbid.passwall." + obj_cbi_id + ".address").value;
									var obj_port = document.getElementById("cbid.passwall." + obj_cbi_id + ".port").value;
								<% end %>
								
								if (address == obj_address && port == obj_port) {
									auto_ping_value[i].setAttribute("has_ping", "1");
									if (result.ping == null || result.ping.trim() == "") {
										auto_ping_value[i].innerHTML = "<font style='color:red'><%:Timeout%></font>";
									} else {
										var ping = parseInt(result.ping);
										if (ping < 100)
											auto_ping_value[i].innerHTML = "<font style='color:green'>" + result.ping + " ms" + "</font>";
										else if (ping < 200)
											auto_ping_value[i].innerHTML = "<font style='color:#fb9a05'>" + result.ping + " ms" + "</font>";
										else if (ping >= 200)
											auto_ping_value[i].innerHTML = "<font style='color:red'>" + result.ping + " ms" + "</font>";
									}
								}
							}
						}
						index++;
						auto_ping();
					},
					function(x) {
						auto_ping_value[index].innerHTML = "<font style='color:red'><%:Timeout%></font>";
						index++;
						auto_ping();
					},
				);
			} else {
				index++;
				auto_ping();
			}
		}
		else {
			index++;
			auto_ping();
		}
	}
	
	auto_ping();
	
	//添加"应用"按钮到"修改"按钮前
	var edit_btn = document.getElementsByClassName("cbi-button cbi-button-edit");
	for(var i = 0; i < edit_btn.length; i++) {
		try {
			var onclick_str = edit_btn[i].getAttribute("onclick");
			var id = onclick_str.substring(onclick_str.lastIndexOf('/') + 1, onclick_str.length - 1);
			var td = edit_btn[i].parentNode;
			var apply = '<input class="cbi-button cbi-button-add" type="button" value="<%:Use%>" onclick="open_set_node_div(\'' + id + '\')" alt="<%:Use%>" title="<%:Use%>" />';
			td.innerHTML = apply + "&nbsp;&nbsp;" + td.innerHTML;
		}
		catch(err) {
			console.error(err);
		}
	}
	
	//]]>
</script>

<div id="set_node_div">
	<div class="cbi-value"><%:You choose node is:%><span id="set_node_name"></span></div>
	<div class="cbi-value">
		<% if tcp_node_num and tonumber(tcp_node_num) >= 1 then %>
			<% for i = 1, tcp_node_num, 1 do %>
				<input class="cbi-button cbi-button-edit" type="button" onclick="set_node('tcp',<%=i%>)" value="TCP_<%=i%>" />
			<% end %>
		<% end %>
		
		<% if udp_node_num and tonumber(udp_node_num) >= 1 then %>
			<% for i = 1, udp_node_num, 1 do %>
				<input class="cbi-button cbi-button-edit" type="button" onclick="set_node('udp',<%=i%>)" value="UDP_<%=i%>" />
			<% end %>
		<% end %>
		
		<% if socks_node_num and tonumber(socks_node_num) >= 1 then %>
			<% for i = 1, socks_node_num, 1 do %>
				<input class="cbi-button cbi-button-edit" type="button" onclick="set_node('socks',<%=i%>)" value="Socks_<%=i%>" />
			<% end %>
		<% end %>
		<input class="cbi-button cbi-button-remove" type="button" onclick="close_set_node_div()" value="<%:Close%>" />
	</div>
</div>
